from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from loguru import logger

from ..models.user import user_manager, User

security = HTTPBearer(auto_error=False)


async def get_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
) -> Optional[User]:
    """获取当前用户（可选）"""
    if not credentials:
        return None

    try:
        session_token = credentials.credentials
        user_session = await user_manager.get_session(session_token)
        if not user_session:
            return None

        user = await user_manager.get_user(user_session.username)
        return user
    except Exception as e:
        logger.exception(f"获取当前用户失败: {e}")
        return None


async def require_auth(current_user: Optional[User] = Depends(get_current_user)) -> User:
    """要求用户认证"""
    if not current_user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未认证或会话已过期，请先登录",
            headers={"WWW-Authenticate": "Bearer"},
        )

    if not current_user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="用户账号已被禁用"
        )
    return current_user


async def require_admin(current_user: User = Depends(require_auth)) -> User:
    """要求管理员权限"""
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="需要管理员权限"
        )
    return current_user


async def get_current_user_optional(
    current_user: Optional[User] = Depends(get_current_user)
) -> Optional[User]:
    """获取当前用户（可选，不抛出异常）"""
    return current_user
